<%@page language="abap"%>
<!DOCTYPE HTML>
<html>
<head>
<title>BI Apps - Report Catalog Administration</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="Stylesheet" type="text/css" href="../theme/css/style_reset.css"/>
<link rel="Stylesheet" type="text/css"href="../theme/css/style_admin_tabs.css"/>
<link rel="Stylesheet" type="text/css"href="../theme/css/button_content.css"/>
<link rel="Stylesheet" type="text/css"href="../theme/css/form_content.css"/>
<script type="text/JavaScript" src="../api/js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="../api/js/jquery.maxlength-min.js"></script>
<script type='text/JavaScript' src='../../zbw_reporting/scripts/framework_include.js'></script>

<script type="text/javascript">
// otaism2a: 28,1,2014 to reduce multiple BOI.js while loading
var BOI = parent.BOI;
var app = {};
var node_id;
var updateNode = true;
$(document)
        .ready(
        function () {
            $('#submit').live('click', function () {
                request();
            });
            $("#reset").live('click', function () {
                window.location.href = window.location.href;
            });
            //bind input change events for app info NODE_INFO
            $(
                    'form li[node] input[name], form li[node] textarea[name], form li[node] select[name]')
                    .live('change', function () {
                        app[$(this).attr('name')] = $(this).val();
                        if ($(this).attr("type") == "checkbox")
                            if ($(this).is(':checked'))
                                app[$(this).attr('name')] = "X";
                            else
                                app[$(this).attr('name')] = "";
                    });
            if (parent.app_id)
                node_id = parent.app_id;
            load();
        });

function request() //genereates request XML
{
    var record, class_name, method_name, req, param, done = 0;
    method_name = $('form:first').attr("METH_NAME");
    record = new BOI.BOIData.Record();
    class_name = "ZCL_MYBW_APP_CATALOG";

    for (var i in app) {
        //ANSAJ,SALEH,22/1/2014 ADD ENCODE CODE BEFORE PERFORMING A POST REQUEST
        if (i == "DESCRIPTION") {
            app["DESCRIPTION"] =unescape(app["DESCRIPTION"]);
            app["DESCRIPTION"] = encodeURIComponent(app["DESCRIPTION"]);
            param = new BOI.BOIData.Parameter();
            param.name = i;
            param.values = app[i] == null ? [ "" ] : [ app[i] ];
            record.parameters.push(param);
        }
        else if (i) {
            param = new BOI.BOIData.Parameter();
            param.name = i;
            param.values = app[i] == null ? [ "" ] : [ app[i] ];
            record.parameters.push(param);
        }
    }
    req = BOI.BOIData.request.prepare(class_name, method_name,
            [ record ]);
    BOI.BOIData.request.perform(req, 'text', 'POST', function (data) {
        if (BOI.BOIData.util.isXML(data)) {
            if (method_name == 'CREATE') {
                var key = $(data).find('APP_ID').text();
                parent.refreshApps(key);
            } else {
                parent.refreshApps(parent.current_app.data.key);
            }
            //alert('Done');
            BOI.BOILib.Util.log('Done', true);

        } else
        //alert('invalid xml');
            BOI.BOILib.Util.log('invalid xml', true);
    });
}

//initialization
function load() {
    var app_id, node_type, description, title, editable, url, parent_id, node_id, role;
    app_id = parent.current_app.data.key;
    if (parent.current_app == undefined) {
        return;
    }
    if (app_id) {
    }
    app_id = parent.current_app.data.key;
    node_type = parent.current_app.data.type;
    //  SALEH,23/1/2014 ADD DECODE CODE ON LOADING TO SHOW THE ACCTUAL STRING
    description = parent.current_app.data.description;
    description = decodeURIComponent(description);
    title = parent.current_app.data.title;
    editable = parent.current_app.data.editable;
    url = parent.current_app.data.href;
    node_id = parent.current_app.data.nodeID;
    role = parent.current_app.data.role;
    //if(parent.current_node.getParent()) parent_id = parent.current_node.getParent().data.nodeID;

    if (app_id == undefined) {
        singleSelector($('#OPEN_STYLE'));
        $('form:first').attr("METH_NAME", "CREATE");
        $('#NODE_TYPE').val(node_type);
        $('#AUTH').val(role);
        app['PARENT_ID'] = node_id;
        app['APP_ID'] = app_id;
        app['TECH_NAME'] = "";
        app['TITLE'] = "New";
        app['DESCRIPTION'] = "New";
        app['NODE_TYPE'] = node_type;
        app['BW_ROLE'] = role;
        app['DISPLAY_ORDER'] = "0";
        app['OPEN_STYLE'] = "";
        app['URL'] = "";
        app['CUSTOM_SCRIPT'] = "";
        app['OTHER_DETAILS'] = "";
        app['HOME_REPORT'] = "";
        app['REMOVE_HOME']="";
        app['THEME']="";
        multiSelector($('#BW_ROLE'));
        setVisibility(node_type, editable);
        $('form').show();
        return;
    }
    //hide the form and show loading image
    $('form').hide();
    $('body').append(BOI.BOIData.render.loading(window.location.href));

    //load app details
    BOI.BOIData.read.getApp(app_id, function (data) {
        //set values
        var form = $('form').first();
        $(data).children().each(function () {
            var tag = $(this).get(0).tagName;
            form.find('#' + tag).val($(this).text());
            // 2/2/2014 :Ansaj added for read the check box data
            if (form.find('#' + tag).attr("type") == "checkbox")
                if ($(this).text() == "X"){
                    form.find('#' + tag).attr("checked", "checked");
                }
            app[tag] = $(this).text();
            //form.find('#' + tag).val($(this).text().replace(/|/g,"\n"));
        });
        //fetched values from tree
        $('#APP_ID').val(app_id);
        $('#NODE_TYPE').val(node_type);
        $('#TITLE').val(title);
        //  SALEH,23/1/2014 ADD DECODE CODE ON LOADING TO SHOW THE ACCTUAL STRING
        $('#DESCRIPTION').val(description);
        $('#TECH_NAME').val(app_id);
        $('#URL').val(url);
        singleSelector($('#OPEN_STYLE'));
        multiSelector($('#BW_ROLE'));

        setVisibility(node_type, editable);
        if (!editable) {
            updateNode = false;
        }
        //show form
        $('body').find('.bi_loading').remove();
        $('form').fadeIn();
    });
}

//transforms input element to a multivalue control
function multiSelector(element, valFn) {
    //element must be accept a val() and must be a JQuery Object
    //it must have a name attribute so it will be used.

    var elval = element.val();
    var elname = element.attr('name');

    var container = $('<div class="bi_ct"></div>');
    container = container.insertAfter(element);

    var clear = $('<div class="bi_clear"></div>');
    clear.insertAfter(container);

    container.append(element);

    var button = $('<input type="button" value="Add" />');
    button = container.append(button);

    var table = $("<table class='bi_ct_tbl'><tbody></tbody></table>");
    container.append(table);

    var data = $('<input type="hidden" name="' + elname + '" value="' + elval + '" />');
    container.append(data);

    element.removeAttr("name");

    var row = '<tr><td>{0}</td><td><span>Remove</span></td></tr>';

    //parse data
    var values = [];

    if (data.val())
        values = data.val().replace(/~/g, '|').split('|');

    for (var i in values)
        if (values[i]) {
            var tr = row.replace('{0}', values[i]);
            table.find('tbody').append(tr);
        }

    element.val('');

    var add = function () {

        var evalue = element.val();
        if (evalue.trim().length == 0)
            return;

        var exists = false;
        table.find('td').each(function () {
            if ($(this).html() == evalue)
                exists = true;
        });
        if (exists)
            return;

        //Perform validation here on element val
        BOI.BOIData.check.validateRole(evalue, function (result) {
            if (result) {
                var tr = row.replace('{0}', evalue);
                table.find('tbody').append(tr);

                //read values again
                refresh();
                element.val('');
            } else
            //alert('Role does not exist');
                BOI.BOILib.Util.log('Role does not exist', true);
        });
    };

    var refresh = function () {
        //read values again
        var newvals = "";
        data.val(newvals);

        table.find('tr').each(function () {
            newvals += $(this).find('td:first').html() + "|";
        });
        if (newvals.indexOf("|") > -1)
            newvals = newvals.substr(0, newvals.length - 1);

        data.val(newvals);
        data.trigger('change');
    };

    //bind events
    element.click(function (e) {
        return false;
    });
    element.keypress(function (e) {
        if (e.keyCode == 13) {
            // enter pressed
            add();
            return false;
        } else if (e.keyCode == 32)
            return false; //space
    });
    /**/

        //remove event
    $('.bi_ct_tbl span').live('click', function () {

        $(this).parent().parent().remove();

        //read values again
        refresh();
    });

    //add event
    button.on('click', add);

    return container;
}

//transforms input element to a select with custom value control
function singleSelector(element) {
    //preload open style options
    BOI.BOIData.lookup
            .getOpenStyles(function (options) {
        var elval = element.val();
        var elname = element.attr('name');

        var container = $('<div class="bi_ct"></div>');
        container = container.insertAfter(element);

        var clear = $('<div class="bi_clear"></div>');
        clear.insertAfter(container);

        var div = $('<div style="height:10px;"></div>');
        var span = $('<span>Specify: </span>');
        container.append(div);
        container.append(span);
        container.append(element);

        var dropdown = $('<select></select>');
        $(options).find('ITEM').each(
                function () {
                    var option = "<option value='"
                            + $(this).find('VALUE').text() + "'>"
                            + $(this).find('NAME').text()
                            + "</option>";
                    dropdown.append(option);
                });
        dropdown.insertBefore(div);

        var data = $('<input type="hidden" name="' + elname + '" value="' + elval + '" />');
        container.append(data);

        //pre select
        if (elval && elval.length > 0) {
            data.val(elval);
            var found = false;
            dropdown.find('option').each(function () {
                //loop over options to see if value exists to preselect it
                if ($(this).val() == elval) {
                    found = true;
                    dropdown.val(elval);
                }
            });
            if (!found) {
                dropdown.val("");
                element.show();
                span.show();
            } else {
                element.hide();
                span.hide();
            }
            data.trigger('change');
        } else //no value
        {
            dropdown.val("");
            data.val('');
            element.show();
            span.show();
            data.trigger('change');
        }

        //bind change event
        dropdown.on('change', function () {
            if (dropdown.val() == dropdown.find('option').last()
                    .val()) //if last element then show custom box
            {
                element.show();
                span.show();
                data.val(element.val());
            } else {
                element.hide();
                span.hide();
                data.val(dropdown.val());
            }
            data.trigger('change');
        });

        //bind text modify
        element.on('keyup', function () {
            data.val(element.val());
            data.trigger('change');
        });
        return container;
    });
}

function setVisibility(node_type, editable) {
    switch (node_type) //what to show
    {
        case "GROUP":
            $('form:first ul li').each(
                    function () {
                        var element = $(this).find('[name]').attr('name');
                        switch (element) {
                            case 'APP_ID':
                            case 'APP_TYPE':
                            case 'URL':
                            case 'OPEN_STYLE':
                                $(this).hide();
                                break;
                            default:
                                if (!editable)
                                    $(this).find(
                                            'input[type="text"],select,textarea')
                                            .attr('readonly', 'readonly');
                                break;
                        }
                    });
            if (!editable) {
                $('form:first').find('input[type="text"],select,textarea')
                        .attr('readonly', 'readonly');
                $('form:first').find(
                        'input[type="button"],input[type="submit"]').hide();
            }
            break;
        default:
            $('form:first ul li').each(
                    function () {
                        var name = $(this).find('[name]').attr('name');
                        switch (name) {
                            case 'APP_TYPE':
                            case 'URL':
                                $(this).hide();
                                break;
                            case 'APP_ID':
                                if ($('form:first').attr("METH_NAME") == 'UPDATE')
                                    $(this).find('#' + name).attr('readonly',
                                            'readonly');
                                break;
                            case 'BW_ROLE':
                            case 'DISPLAY_ORDER':
                                if (!editable)
                                    $(this).hide();
                                break;
                            default:
                                if (!editable) {
                                    $(this).find(
                                            'input[type="text"],select,textarea')
                                            .attr('readonly', 'readonly');
                                    $(this).find('#OPEN_STYLE').removeAttr(
                                            'readonly');
                                }
                                break;
                        }
                    });
            break;
    }
}
</script>
<script type="text/javascript">
    $(document).ready(function () {
    $("#APP_ID").keyup(function () {
        var upperCase = new RegExp('[A-Z0-9_]');
        var appname = $("#APP_ID").val();
        for (var i in appname) {
            if (appname[i].match(upperCase)) {
                //app['APP_ID'] = appname[i];
                $("#APP_ID")[0].style.backgroundColor = "";
            }
            else {
                //$("#APP_ID").val('');
                $("#APP_ID")[0].style.backgroundColor = "LightCoral";
                $("#APP_ID").val(appname.substring(0,i)) ;

                break;
            }
        }
    });
    $("#APP_ID").bind('change', function () {
        app['APP_ID'] = $("#APP_ID").val();
    });
    $("#APP_ID").maxlength({
        events:[], // Array of events to be triggerd
        maxCharacters:32, // Characters limit
        status:false, // True to show status indicator bewlow the element
        statusClass:"status", // The class on the status div
        statusText:"character left", // The status text
        notificationClass:"notification", // Will be added when maxlength is reached
        showAlert:true, // True to show a regular alert message
        alertText:"You have typed too many characters.", // Text in alert message
        slider:false
        // True Use counter slider
    });

    $('#DESCRIPTION').maxlength({
        events:[], // Array of events to be triggerd
        maxCharacters:201, // Characters limit
        status:true, // True to show status indicator bewlow the element
        statusClass:"status", // The class on the status div
        statusText:"character left", // The status text
        notificationClass:"notification", // Will be added when maxlength is reached
        showAlert:false, // True to show a regular alert message
        alertText:"You have typed too many characters.", // Text in alert message
        slider:false
        // True Use counter slider
    });
    // saleh 27,1,2014 for description coloring if max characters is reached
    $("#DESCRIPTION").keyup(function () {

        if ($("#DESCRIPTION").val().length == 201) {
            $("#DESCRIPTION")[0].style.backgroundColor = "LightCoral";
        }
        else if ($("#DESCRIPTION").val().length <= 200 && $("#DESCRIPTION").val().length >= 0) {
            $("#DESCRIPTION")[0].style.backgroundColor = "";
        }
    });
    });
</script>
</head>
<body>
<div class="tab-frame bi_admin_app_edit">
    <form method="post" meth_name="UPDATE" style="">
        <h2>Report Catalog Administration</h2>
        <ul>
            <li node="1"><label for="APP_ID">App ID:</label><input
                    id="APP_ID" name="APP_ID" type="text"/>
            </li>
            <li node="1"><label for="NODE_TYPE">Type:</label><input
                    id="NODE_TYPE" name="NODE_TYPE" type="text" readonly="readonly"/>
            </li>
            <li node="1"><label for="TITLE">Title:</label><input id="TITLE"
                                                                 name="TITLE" type="text"/>
            </li>
            <li node="1"><label for="DESCRIPTION">Description:</label>
                <textarea rows="3" id="DESCRIPTION" name="DESCRIPTION"></textarea>
            </li>
            <li node="1"><label for="URL">URL:</label><input id="URL"
                                                             name="URL" type="text"/>
            </li>
            <li node="1"><label for="BW_ROLE">Authorization:</label><input
                    type="text" id="BW_ROLE" name="BW_ROLE"/>
            </li>
            <li node="1"><label for="OPEN_STYLE">Open Style:</label><input
                    id="OPEN_STYLE" name="OPEN_STYLE" type="text"/>
            </li>
            <li node="1"><label for="DISPLAY_ORDER">Display Order:</label><input
                    id="DISPLAY_ORDER" name="DISPLAY_ORDER" type="text"
                    onkeypress="if (event.keyCode < 48 || event.keyCode > 57) return false;"/>
            </li>
            <li node="1"><label for="HOME_REPORT">Home Report:</label><input
                    id="HOME_REPORT" name="HOME_REPORT" type="text"/>
            </li>
            <li node="1"><label for="CUSTOM_SCRIPT">Custom Script
                URL:</label><input id="CUSTOM_SCRIPT" name="CUSTOM_SCRIPT" type="text"/>
            </li>
            <li node="1"><label for="OTHER_DETAILS">Other Details:</label>
                <textarea rows="3" id="OTHER_DETAILS" name="OTHER_DETAILS"></textarea>
            </li>
            <li node="1">
                <label for="REMOVE_HOME">Remove Home Report in Catalog ?</label>
                <div class="input-hidden" style="text-align: left"></div>
                <input id="REMOVE_HOME" name="REMOVE_HOME" type="checkbox" />
            </li>
            <li node="1">
                <label for="THEME">Theme :</label>
                <input id="THEME" name="THEME" type="text"/>
            </li>
            <li>
                <!--  <label for="submit"></label>-->
                <a id="submit" class="button-content-YW" href="#"><span>Save</span> </a>
            </li>
        </ul>
    </form>
</div>
</body>
</html>